// 退款订单租借
import { OrderItem } from '@/pages/OrderCabinet';
import { Descriptions, InputNumber, message, Spin } from 'antd';
import Modal, { ModalFuncProps } from 'antd/lib/modal/Modal';
import React, { useState } from 'react';
import { leaseOrderRefund, LeaseOrderRefundParamsType } from '@/services/order';
import { connect, CurrentUser } from 'umi';
import { ConnectState } from '@/models/connect';
import { LinearOrderItem } from '@/pages/OrderPowerline';

interface RefundModalProps {
  visible: boolean;
  onCancel: Function;
  onSuccess: Function;
  order?: OrderItem | LinearOrderItem;
  userState?: CurrentUser;
  order_type: number;
}

let config: ModalFuncProps = {
  title: '提示',
  content: <>确定要退款吗?</>,
  cancelText: '取消',
  okText: '退款',
};

// Modal
const RefundModal: React.FC<RefundModalProps> = (props) => {
  const { visible, onCancel, onSuccess, order, userState, order_type } = props;
  const [refundAmount, setRefundAmount] = useState(0); // 退款金额
  const [loading, setLoading] = useState(false); // 是否刷新
  const [modal, contextHolder] = Modal.useModal();

  const onChange = (value: number | undefined | string) => {
    setRefundAmount(Number(value));
  };

  const toConfirm = () => {
    config.onOk = (close) => {
      close();
      const data: LeaseOrderRefundParamsType = {
        uId: userState?.id!,
        userType: userState?.user_type!,
        token: userState?.token!,
        order_no: order?.order_no!,
        order_type: order_type,
        refund_amount: refundAmount,
      };
      setLoading(true);
      leaseOrderRefund(data)
        .then((res) => {
          setLoading(false);
          if (res.code == 0) {
            message.success('退款成功!');
            onCancel();
            onSuccess();
          }
        })
        .catch((err) => {
          setLoading(false);
          console.log(err);
          message.error('退款失败，请重试!');
        });
    };
    modal.confirm(config);
  };
  return (
    <>
      <Modal
        cancelText="取消"
        okText="退款"
        key="1"
        title="订单退款"
        visible={visible}
        onOk={() => toConfirm()}
        onCancel={() => onCancel()}
      >
        <Spin spinning={loading}>
          <Descriptions bordered={true} column={1}>
            <Descriptions.Item label="订单金额">
              {order ? order.real_amount : '--'}
            </Descriptions.Item>
            <Descriptions.Item label="退款金额">
              <InputNumber
                min={0}
                max={order && order.real_amount ? Number(order.real_amount) : 0}
                defaultValue={0}
                onChange={onChange}
              ></InputNumber>
            </Descriptions.Item>
          </Descriptions>
        </Spin>
      </Modal>
      {contextHolder}
    </>
  );
};

export default connect(({ user }: ConnectState) => ({ userState: user.currentUser }))(RefundModal);
